package com.qire.manhua.controller;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.qire.antsrouter.AntsRouter;
import com.qire.antsrouter.card.FloorCard;
import com.qire.common.basic.ObjectUtil;
import com.qire.common.constant.AdvertManage;
import com.qire.common.constant.Navigation;
import com.qire.common.model.entity.UserEntity;
import com.qire.common.support.base.EventController;
import com.qire.common.utils.EquipmentInfoUtil;
import com.qire.common.utils.ToastHelper;
import com.qire.common.widget.adapter.auto.AutoVariable;
import com.qire.common.widget.snackbar.Prompt;
import com.qire.manhua.BR;
import com.qire.manhua.activity.ComicReaderActivity;
import com.qire.manhua.activity.helper.LoginRouter;
import com.qire.manhua.dialog.MessageEnablePromptDialog;
import com.qire.manhua.dialog.ShareComicDialog;
import com.qire.manhua.dialog.UnlockChapterOnComicReaderDialog;
import com.qire.manhua.model.entity.ComicBookEntity;
import com.qire.manhua.model.entity.ComicBookEntity.DirectoryInfo;
import com.qire.manhua.model.entity.ComicBookEntity.ChaptersInfo;
import com.qire.manhua.model.viewModel.impl.UnlockChapterDialogViewModel;
import com.qire.manhua.model.viewModel.impl.ComicReaderViewModel;
import com.qire.manhua.model.viewModel.impl.ComicReaderViewModel.ComicReaderItemViewModel;
import com.qire.manhua.model.viewModel.impl.ComicReaderViewModel.ComicReaderItemViewModel.ComicReaderCommentItemViewModel;
import com.qire.manhua.view.comicReader.LoopComicReaderView.ComicReaderListener;
import com.qire.other.recorder.ComicActionRecorder;

import androidx.annotation.NonNull;
import androidx.databinding.ViewDataBinding;

public class ComicReaderController extends EventController<ComicReaderActivity> implements AutoVariable {

    private ComicReaderViewModel    viewModel;

    public ComicReaderController(@NonNull ComicReaderActivity activity) {
        super(activity);
    }

    @Override
    protected void bindView() {
        owner.viewDataBinder().setVariable(BR.comicReaderController,this);
    }

    @Override
    public void bindVariable(ViewDataBinding viewBind) {
        viewBind.setVariable(BR.comicReaderController,this);
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        this.viewModel = null;
    }

    public void onAddition(ComicReaderViewModel viewModel) {
        this.viewModel = viewModel;
    }

    /*************************************************************************************************************************/

    //region    #topNavBar 顶部导航菜单事件 begin
    /** 导航条：退回按钮单击事件*/
    public void closeBtnOnClick(View view) {
        owner.onBackPressed();
    }
    /** 导航条：打开更多菜单栏按钮事件*/
    public void openMoreBarBtnOnClick(View view) {
        viewModel.toggleMoreMenu();
    }
    //endregion #topNavBar 顶部导航菜单事件 end


    //region    #bottomMenuBar 底部菜单栏 事件响应 begin
    /** 底部浮层菜单：弹幕开关按钮状态切换事件*/
    public void bulletSwitchOnCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        ToastHelper.showSnackBar(isChecked ? "已为你开启弹幕" : "弹幕已关闭", Prompt.SUCCESS);
        viewModel.bulletSwitch(isChecked);
    }

    /** 底部浮层菜单：打开弹幕编辑按钮单击事件*/
    public void bulletScreenBtnOnClick(View view) {
        // todo 这里应该提交一个弹幕信息过去，否则的话，第二次编辑就会丢失文字颜色。
        TextView textView = ObjectUtil.as(view, TextView.class);
        if(ObjectUtil.nonNull(view)) {
            viewModel.foldingMenu();

            String contentText = textView.getText().toString();

            AntsRouter.ROUTER.<FloorCard>buildCard(Navigation.Page.BulletScreenDialogPage)
                    .withData("contentText", contentText)
                    .navigation();
        }
    }

    /** 底部浮层菜单：发送弹幕按钮单击事件*/
    public void bulletScreenSendBtnOnClick(View view) {
        viewModel.submitBullet();
    }

    /** 底部浮层菜单：上一章按钮单击事件*/
    public void previousChapterBtnOnClick(View view) {
        viewModel.pageTurning(false);
    }

    /** 底部浮层菜单：下一章按钮单击事件*/
    public void nextChapterBtnOnClick(View view) {
        viewModel.pageTurning(true);
    }

    /** 底部浮层菜单：目录按钮单击事件*/
    public void directoryBtnOnClick(View view) {
        AntsRouter.ROUTER.<FloorCard>buildCard(Navigation.Page.ComicDirectorySelectorPage)
                .withData("comicBookEntity", viewModel.comicBookEntity())
                .navigation();
    }

    /** 底部浮层菜单：收藏按钮单击事件*/
    public void favoritesBtnOnClick(View view) {
        if(LoginRouter.ROUTER.checkLoginRouteIfNeed()) {
            return;
        }
        viewModel.whetherToFavorites(false);

        MessageEnablePromptDialog.showIfNeed(view.getContext());
    }

    /** 更多底部浮层菜单：下载按钮单击事件*/
    public void downloadBtnOnClick(View view) {
        AntsRouter.ROUTER.<FloorCard>buildCard(Navigation.Page.ComicDownloadSelectorPage)
                .withData("comicBookEntity", viewModel.comicBookEntity())
                .navigation();
        // 行为数据统计
        ComicActionRecorder.build(ComicActionRecorder.count_down)
                .setSource("阅读页")
                .setComicInfo(viewModel.comicBookEntity().id, viewModel.comicBookEntity().bookName)
                .doRecorde(view.getContext());
    }
    //endregion #bottomMenuBar 底部菜单栏 事件响应 end


    //region    #ComicReaderMoreBar 更多底部浮层菜单 begin
    /** 更多底部浮层菜单：详情按钮单击事件*/
    public void detailsBtnOnClick(View view) {
        AntsRouter.ROUTER.<FloorCard>buildCard(Navigation.Page.ComicDetailPage)
                .withData("comicBookId", viewModel.comicBookEntity().id)
                .go();

        if(!owner.isFinishing()) {
            owner.finish();
        }
    }

    /** 更多底部浮层菜单：评论按钮单击事件*/
    public void commentsBtnOnClick(View view) {
        AntsRouter.ROUTER.<FloorCard>buildCard(Navigation.Page.ComicCommentPage)
                .withData("comicBookEntity", viewModel.comicBookEntity())
                .navigation();
    }

    /** 更多底部浮层菜单：分享按钮单击事件*/
    public void shareBtnOnClick(View view) {
        new ShareComicDialog(view.getContext(), viewModel.shareInfo()).show();
    }
    //endregion #ComicReaderMoreBar 更多底部浮层菜单 end


    //region    #LoopComicReaderView 循环漫画阅读器 begin
    /**
     * LoopComicReaderView 监听回掉事件
     * */
    public final ComicReaderListener comicReaderListener = new ComicReaderListener() {

        private final Handler popUpHandler = new Handler(this::handleMessage);
        private final int popUpReaderFinish = 1;
        private final int deletePopUpReaderFinish = 2;

        public boolean handleMessage(Message msg){
            switch (msg.what){
                case popUpReaderFinish:
                    AntsRouter.ROUTER.<FloorCard>buildCard(Navigation.Page.ComicReaderFinishPage)
                            .withData("comicBookId", viewModel.comicBookEntity().id)
                            .navigation();
                    break;
                case deletePopUpReaderFinish:
                    popUpHandler.removeMessages(popUpReaderFinish);
                    break;
            }
            return true;
        }

        @Override
        public void onPreRead(int preReadItemIndex, int totalItemCount) {

            /**************************************************************************
             * 1.排除越界等意外情况(没有章节数据，当前阅读超过章节范围)
             * 2.通过索引查找到预加载章节
             * 3.预读章节信息
             *************************************************************************/

            if (totalItemCount == 0) {
                return;
            }

            if (preReadItemIndex < 0 || preReadItemIndex > totalItemCount) {
                return;
            }

            ChaptersInfo preloadChapters = viewModel.findChapterBy(preReadItemIndex);
            if (preloadChapters == null) {
                return;
            }

            viewModel.preReadChapterBy(preloadChapters);

        }

        @Override
        public void onReading(int currentVisibleItemIndex, int totalItemCount) {

            /**************************************************************************
             * 1.排除越界等意外情况(没有章节数据，当前阅读超过章节范围)
             * 2.通过索引查找阅读章节
             * 4.阅读章节
             * 5.更新底部进度
             * 6.保存历史记录
             * 7.上报阅读记录
             *************************************************************************/

            if (totalItemCount == 0) {
                return;
            }

            if (currentVisibleItemIndex < 0 || currentVisibleItemIndex > totalItemCount) {
                return;
            }

            ChaptersInfo readyReadChapter = viewModel.findChapterBy(currentVisibleItemIndex);

            if (readyReadChapter == null) {
                ToastHelper.showToast("可能由于网络问题导致阅读章节数据不存在，请退出重新阅读");
                return;
            }

            viewModel.readChapterBy(readyReadChapter);

//            // 保存历史记录
//            DBBook bookPO = new DBBook(comicBookEntity.id, comicBookEntity.bookName, readyReadChapters.id);
//            DBManager.getInstance().saveBook(bookPO);
//            bindingView.getComicReaderPopularHelperPresenter().reportComicPopular();
            owner.reportComicPopular();
        }

        @Override
        public boolean onCheckUnlock(int unlockItemIndex, int totalItemCount) {

            //解决方案：
            //NOTE: 哨兵机制:对于滑动行为和特殊操作中设立onCheckUnlock过滤，如果返回false则可以基于执行，否则停止滑动或特殊操作。
            //NOTE: 特殊操作:例如适配数据fill数据时

            if(totalItemCount == 0)
                return false;
            if(unlockItemIndex <0 || unlockItemIndex >= totalItemCount)
                return false;
            if(viewModel == null)
                return false;

            ComicBookEntity comicBookEntity     = viewModel.comicBookEntity();
            DirectoryInfo   readyReadDirectory  = comicBookEntity.findDirectoryInfo(unlockItemIndex);
            if(ObjectUtil.isNull(readyReadDirectory)) {
                // todo : unlockItemIndex 游标越界了。
                return false;
            }
            ChaptersInfo    readyReadChapters   = readyReadDirectory.chaptersInfo;

//            ComicReaderListItemModel    readyReadItemModel  = viewModel.pickReadyUnlockItemModel(unlockItemIndex);
//            ChaptersInfo                readyReadChapters   = readyReadItemModel.chaptersInfo;
//            DirectoryInfo               readyReadDirectory  = readyReadChapters.directoryInfo();

            //NOTE: 章节解锁流程：
            //NOTE: 1.根具目录对象判断当前章节是否有锁,如果无锁则返回false。
            //NOTE: 2.根具章节对象判断当前章节是否已经解过锁,如果解过锁则返回false
            //NOTE: 3.开始解锁弹窗，进入解锁业务.
            if(!readyReadDirectory.haveLock()) {
//                comicBookEntity.lockInfo().disableFirstUnlock();
                return false;
            }
            if(!readyReadChapters.needUnlock())
                return false;

            // 停止漫画阅读器继续滚动
            owner.viewDataBinder().comicReaderListView.stopFlingAndDock();

            //NOTE: 进入解锁业务流程：
            //NOTE: 1.自动解锁：
            //      1)检查是否开启自动解锁，开启自动解锁才能进入自动解锁流程
            //      2)检查是否是首次进入，不是首次进入才能进入自动解锁流程
            //      3)检查余额是否足够，余额足够才能进入自动解锁流程
            //      4)检查版权是否过期,非版权过期书籍才能进入自动解锁流程
            //      5)检查是否可以广告解锁，章节可以广告解锁且用户当日广告解锁次数未使用完则弹出广告解锁，否则自动解锁
            //      满足以上条件则直接阅读章节
            //NOTE: 2.手动解锁：判定解锁浮层是否开启，如果未开启则打开浮层进入手动支付解锁业务
            UnlockChapterDialogViewModel unlockDialogViewModel = new UnlockChapterDialogViewModel();
            unlockDialogViewModel.loadComicData(comicBookEntity, readyReadDirectory);

            boolean enableAutoUnlock = UserEntity.self.isAutoPay();
            enableAutoUnlock &= !comicBookEntity.lockInfo().needFirstUnlock();
            enableAutoUnlock &= (!unlockDialogViewModel.isInsufficientBalanceByPanel());
            enableAutoUnlock &= (!comicBookEntity.lockInfo().isCopyrightExpired());
            enableAutoUnlock &= !(readyReadDirectory.canUnlockedByAd() && UserEntity.self.canAdUnlocked());
            if(enableAutoUnlock) {
                onReading(unlockItemIndex, totalItemCount);
                // 修改自动解锁状态也需要拦截，否则放行会导致接口数据还未返回而滑动事件继续导致解锁的章节不能加载全部图片数据从而快速闪过。
                return true;
            }

            UnlockChapterOnComicReaderDialog unlockDialog = viewModel.fetchChaptersUnlockDialog(owner, unlockDialogViewModel);

            if(unlockDialog.isShowing()) {
                return true;
            }

            //TODO：不是特别好的解决方案，值得注意观察：解决从没有提前判断是否需要解锁的页面跳转到阅读页的情况
            final boolean notStartRead = viewModel.notStartRead();
            if(notStartRead) {
                unlockDialog.setOnCancelListener(dialog -> owner.onBackPressed());
            }

            unlockDialog.show();

            //如果余额不足时，去检查首充福利是否还可用。
            if(unlockDialogViewModel.isInsufficientBalance()) {
                viewModel.welfareCheck(true);
            }

            return true;
        }

        private long lastReachEdgeTime = 0;
        @Override
        public void onSlideToEdge(int currentVisibleItemIndex, int totalItemCount) {
            if(currentVisibleItemIndex + 1 >= totalItemCount) {
                long currentTime = System.currentTimeMillis();
                if(300 > (currentTime - lastReachEdgeTime)) {
                    popUpHandler.removeMessages(deletePopUpReaderFinish);
                } else {
                    // 停止漫画阅读器继续滚动
                    owner.viewDataBinder().comicReaderListView.stopFlingAndDock();
                    popUpHandler.sendEmptyMessageDelayed(popUpReaderFinish, 300);
                }
                popUpHandler.sendEmptyMessageDelayed(deletePopUpReaderFinish, 50);
                lastReachEdgeTime = currentTime;
            }
        }
    };

    public void reportBtnOnClick(View view) {
        // 举报评论按钮事件，目前需求以移除，如果3个版本内不恢复则可以删除，当前版本2.4.5
    }

    public void giveLikeCommentBtnOnClick(View view) {
        ComicReaderCommentItemViewModel itemViewModel = ObjectUtil.as(view.getTag(), ComicReaderCommentItemViewModel.class);
        if(ObjectUtil.isNull(itemViewModel)) {
            return;
        }
        if(itemViewModel.isMyLike()) {
            ToastHelper.showToast("您已经点过赞了");
            return;
        }
        itemViewModel.giveAlike();
    }

    public void commentBtnOnClick(View view) {
        // 回复评论按钮事件，目前需求以移除，如果3个版本内不恢复则可以删除，当前版本2.4.5
    }

    /**
     * 点赞按钮单击事件*/
    public void giveLikeBtnOnClick(View view) {
        ComicReaderItemViewModel itemViewModel = ObjectUtil.as(view.getTag(), ComicReaderItemViewModel.class);
        if(ObjectUtil.nonNull(itemViewModel)) {
            itemViewModel.giveLike();
        }
    }

    /**
     * 查看更多按钮单击事件*/
    public void seeMoreBtnOnClick(View view) {
        ComicReaderItemViewModel itemViewModel = ObjectUtil.as(view.getTag(), ComicReaderItemViewModel.class);
        if(ObjectUtil.nonNull(itemViewModel)) {
            AntsRouter.ROUTER.<FloorCard>buildCard(Navigation.Page.ComicCommentListPage)
                    .withData("comicBookEntity", viewModel.comicBookEntity())
                    .withData("chapterId", itemViewModel.chapterId())
                    .navigation();
        }
    }

    /**
     * 写评论按钮单击事件*/
    public void writeCommentBtnOnClick(View view) {
        ComicReaderItemViewModel itemViewModel = ObjectUtil.as(view.getTag(), ComicReaderItemViewModel.class);
        if(ObjectUtil.nonNull(itemViewModel)) {
            AntsRouter.ROUTER.<FloorCard>buildCard(Navigation.Page.ComicCommentPage)
                    .withData("comicBookEntity", viewModel.comicBookEntity())
                    .withData("chapterId", itemViewModel.chapterId())
                    .navigation();
        }
    }

    /**
     * 同类型漫画按钮单击事件*/
    public void openSameTypeBtnOnClick(View view) {
        ToastHelper.showToast("openSameTypeBtnOnClick");

//        final ComicReaderViewModel viewModel = bindingView.getComicReaderViewModel();
//        SameTypeBookActivity.start(activity, viewModel.comicBookEntity().id);
    }
    //endregion #LoopComicReaderView 循环漫画阅读器 end


    //region    #UnlockChapterOnComicReaderDialog 章节解锁浮层弹窗事件响应 begin

    public void unlockByBuyBtnOnClick(View view) {
        UnlockChapterDialogViewModel unlockChapterViewModel = ObjectUtil.as(view.getTag(), UnlockChapterDialogViewModel.class);
        if(ObjectUtil.nonNull(unlockChapterViewModel)) {
            int     chapterId       = unlockChapterViewModel.getChapterId();
            String  chapterPrice    = unlockChapterViewModel.getBuyPriceStr();
            // TODO：需要实现API接口的回声功能，将解锁时间移动到API请求回调后，根据API回调的回声传递参数来判定解锁这样可以保证基本同步
            String  paymentType;
            if(unlockChapterViewModel.isBeanUnlockPanel()) {
                paymentType = "bean";
                unlockChapterViewModel.getDirectoryInfo().unlock3Days();
            } else {
                paymentType = "coin";
            }
            viewModel.unlockReadyReadChapterByBuy(chapterId, chapterPrice, paymentType);
        }
    }

    public void unlockByAdBtnOnClick(View view) {
        final UnlockChapterDialogViewModel unlockChapterViewModel = ObjectUtil.as(view.getTag(), UnlockChapterDialogViewModel.class);
        if(ObjectUtil.nonNull(unlockChapterViewModel)) {
            final int chapterId = unlockChapterViewModel.getChapterId();
            final boolean notStartRead = viewModel.notStartRead();

            viewModel.showLoadDialog();

            AdvertManage.AdvertSpace.ComicUnlock.build()
                    .setSize(EquipmentInfoUtil.getScreenWidth(), 0)
//                    .setClosedListener(() -> ToastHelper.showToast("您取消了视频播放，放弃了解锁奖励！"))
                    .setClosedListener(() -> viewModel.unlockReadyReadChapterByAd(chapterId))
                    .setSkippedListener(() -> {
                        UnlockChapterOnComicReaderDialog unlockDialog = viewModel.fetchChaptersUnlockDialog(owner, unlockChapterViewModel);
                        if(unlockDialog.isShowing())
                            return ;
                        //TODO：不是特别好的解决方案，值得注意观察：解决从没有提前判断是否需要解锁的页面跳转到阅读页的情况
                        if(notStartRead) {
                            unlockDialog.setOnCancelListener(dialog -> owner.onBackPressed());
                        }
                        unlockDialog.show();
                    })
                    .setErrorListener(() -> {
                        viewModel.dismissLoadDialog();
                        ToastHelper.showToast("运行错误，请联系客服或稍后再试！");
                    })
                    .setStartListener(viewModel::dismissLoadDialog)
                    .playVideo(owner);
        }
    }

    //endregion #UnlockChapterOnComicReaderDialog 章节解锁浮层弹窗事件响应 end


    public void closeAddFavoritePromptOnClick(View view){
        viewModel.hideFavoritePrompt();
    }

    /** 漫画阅读器View长按事件：弹出弹幕编辑Dialog*/
    public void comicReaderViewOnLongClick(View view){
//        bulletScreenComicReaderView = null;
//        activity.foldingMenu();
//        BulletScreenDialogActivity.start(activity);
    }

    /**
     * 新人特惠入口单击事件
     * @param view
     */
    public void firstBuyCoinViewOnClick(View view) {
        AntsRouter.ROUTER.<FloorCard>buildCard(Navigation.Page.BuyCoinsMarketDialogPage)
                .withData("comicId", viewModel.comicBookEntity().id)
                .navigation();
    }

}
